<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button type="primary" :disabled="isaddress" @click="add()">添加课程</a-button>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-form :inline="true" size="mini">
          <el-form-item label="课程名称">
            <el-input v-model="mname" placeholder="课程名称"></el-input>
          </el-form-item>
          <el-form-item label="校区">
            <el-select v-model="search" placeholder="校区">
              <el-option label="全部校区" value></el-option>
              <el-option
                v-for="(item, i) in getschooladdress"
                :key="`2classroom${i}`"
                :label="item.name"
                :value="item.ID"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="课程状态">
            <el-select v-model="mtype" placeholder="课程状态">
              <el-option label="取消选择" value></el-option>
              <el-option label="可售" value="可售"></el-option>
              <el-option label="停售" value="停售"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-table
          :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
          style="width: 100%; border: 1px solid #eeeeee;"
        >
          <el-table-column prop="ID" label="序号" width="60">
            <template slot-scope="scope">{{scope.$index+1}}</template>
          </el-table-column>
          <el-table-column prop="name" label="课程名称" width="180">
            <template slot-scope="scope">
              <el-button
                type="text"
                v-text="scope.row.name"
                @click="watchthis = true ; index = scope.row.ID"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column prop="type" sortable label="课时数">
            <template slot-scope="scope">{{ classhour(scope.row.ID) }}</template>
          </el-table-column>
          <el-table-column prop="info" label="开班数">
            <template slot-scope="scope">{{ scope.row.schoolclazz.length }}</template>
          </el-table-column>
          <el-table-column prop="studentnum" sortable label="开课校区">
            <template slot-scope="scope">{{ schooladdresss(scope.row.addressids) }}</template>
          </el-table-column>
          <el-table-column prop="type" sortable label="状态"></el-table-column>
          <el-table-column prop="studentnum" sortable label="创建日期">
            <template slot-scope="scope">{{ totime(scope.row.updatedAt) }}</template>
          </el-table-column>
          <el-table-column align="right" label="操作" width="300px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="add(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="del(scope.row.ID)">删除</el-button>
              <el-button
                size="mini"
                :type="danger(scope.row.type)"
                @click="changes(scope.row)"
                v-text="scope.row.type === '停售'?'可售':'停售'"
              ></el-button>
              <el-button size="mini" type="primary">
                <router-link class="text-white" :to="{name:'课时管理', params: { ID: scope.row.ID }}">课时</router-link>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          @current-change="currentChange"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="tableData.length"
        ></el-pagination>
        <el-dialog class="school-form" :title="title" width="510px" :visible.sync="setaddress">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="学年">
              <el-input v-model="ruleForm.schoolyear"></el-input>
            </el-form-item>
            <el-form-item label="学期">
              <el-input v-model="ruleForm.term"></el-input>
            </el-form-item>
            <el-form-item label="开课校区" prop="addressids">
              <el-radio-group v-model="resource">
                <el-radio :label="true">全部校区</el-radio>
                <el-radio :label="false">指定校区</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-checkbox-group class="checkbox-group" v-show="!resource" v-model="checkList">
              <el-checkbox
                v-for="(v, i) in getschooladdress"
                :key="`2user${i}`"
                :label="v.ID.toString()"
              >{{v.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
            <el-button @click="setaddress = false" size="mini">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog class="school-form" title="课程详情" width="510px" :visible.sync="watchthis">
          <el-form class="htedialogtext" v-if="watchthis" label-width="100px" size="mini">
            <el-form-item label="课程名称:">
              <span v-text="scope.name"></span>
            </el-form-item>
            <el-form-item label="学年:">
              <span v-text="scope.schoolyear"></span>
            </el-form-item>
            <el-form-item label="学期:">
              <span v-text="scope.term"></span>
            </el-form-item>
            <el-form-item label="开课校区:">
              <span>{{ schooladdresss(scope.addressids) }}</span>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="watchthis = false" type="primary" plain size="mini">返回</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  asynccreatschoolcourse,
  asyncdelschoolcourse
} from "../../../../plugins/api.js";
import { reduce, filter } from "underscore";
import { totime } from "../../../utils.js";

export default {
  name: "schoolcourse",
  data() {
    return {
      mtype: "",
      mname: "",
      watchthis: false,
      index: 0,
      isaddress: true,
      setaddress: false,
      checkList: [],
      search: "",
      currentPage: 1,
      pagesize: 10,
      title: "添加课程",
      ruleForm: {
        ID: "",
        name: "",
        schoolyear: "",
        term: "",
        type: "可售",
        addressids: "*"
      },
      resource: true,
      rules: {
        name: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        addressids: [
          { required: true, message: "请选择校区", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters([
      "getschoolcourse",
      "getschooladdress",
      "getschoolclasshour",
      "getschoolclazz"
    ]),
    tableData() {
      const { getschoolcourse, search, mname, mtype } = this;
      return getschoolcourse.filter(data => {
        const x = mtype ? data.type == mtype : true;
        const y = mname ? data.name.includes(mname) : true;
        const z = search != "*" ? data.addressids.includes(search) : true;
        return x && y && z;
      });
    },
    scope() {
      return this.getschoolcourse.find(v => v.ID === this.index);
    }
  },
  mounted() {
    if (this.getschooladdress.length) {
      this.isaddress = false;
    }
  },
  methods: {
    totime,
    classhour(id) {
      const data = filter(this.getschoolclasshour, v => v.schoolcourseid == id);
      return reduce(
        data,
        (v, o) => {
          if (!v) {
            return 0 + o.classhour;
          } else {
            return v + o.classhour;
          }
        },
        0
      );
    },
    clazzs(id) {
      return this.getschoolclazz.filter(
        v => v.schoolcourseid == id && v.type == "3"
      ).length;
    },
    danger(type) {
      if (type === "停售") {
        return "info";
      } else {
        return "warning";
      }
    },
    schooladdresss(id) {
      id = String(id);
      if (id === "*") {
        return "全部校区";
      } else {
        let data = id.split(",");
        let arr = [];
        for (let v of this.getschooladdress) {
          if (data.includes(v.ID.toString())) {
            arr.push(v.name);
          }
        }

        return arr.join(" ");
      }
    },
    currentChange(index) {
      this.currentPage = index;
    },
    add(v) {
      this.setaddress = true;
      if (v) {
        this.title = "修改课程";
        this.ruleForm = JSON.parse(JSON.stringify(v));
        const addressids = this.ruleForm.addressids;
        if (addressids === "*") {
          this.resource == true;
        } else if (addressids === "") {
          this.resource == false;
          this.checkList = [];
        } else {
          this.resource == false;
          this.checkList = addressids.split(",");
        }
      } else {
        this.title = "添加课程";
        this.resource == true;
        this.checkList = [];
        this.ruleForm = {
          name: "",
          schoolyear: "",
          term: "",
          addressids: "*"
        };
      }
    },
    del(ID) {
      this.$confirm("此操作将永久删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          if (this.resource) {
            this.ruleForm.addressids = "*";
          } else {
            this.ruleForm.addressids = this.checkList.join(",");
          }
          try {
            await asyncdelschoolcourse({ ID });
            await this.$store.dispatch("actionschoolcourse");

            this.$message.success("删除成功");
          } catch (err) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    changes(row) {
      const { ID, type } = row;
      const t = type === "可售" ? "停售" : "可售";
      this.$confirm(`${t}此该课程, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asynccreatschoolcourse({ ID, type: t });
            await this.$store.dispatch("actionschoolcourse");

            this.$message.success(`${t}成功`);
          } catch (err) {
            this.$message.error(`${t}删除失败`);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    async submitForm() {
      if (this.resource) {
        this.ruleForm.addressids = "*";
      } else {
        this.ruleForm.addressids = this.checkList.join(",");
      }
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          const data = this.ruleForm.ID ? "修改" : " 添加";
          try {
            await asynccreatschoolcourse(this.ruleForm);
            await this.$store.dispatch("actionschoolcourse");
            this.setaddress = false;
            this.$message.success(`${data}成功`);
          } catch (err) {
            this.$message.error(`${data}失败`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");

          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.dialog-footer {
  text-align: center;
}
.checkbox-group {
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 15px;
  padding-bottom: 15px;
  background-color: #ededed;
}
</style>